package netty.com.netty;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;


/**
 * @Title: netty的客户端
 * @Description: netty的客户端
 * @Author: lils
 * @CreateTime: 2018-05-17 14:29
 */
public class nettyClient {


    public static void main(String[] args) {
        // nettyClient服务启动器
        ClientBootstrap clientBootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
        // 设置一个处理服务端消息和各种消息事件的类(Handler)
        clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(new nettyClientHandler());
            }
        });
        // 连接到本地的8000端口的服务端
        clientBootstrap.connect(new InetSocketAddress("127.0.0.1", 8181));
    }

    private static class nettyClientHandler extends SimpleChannelHandler {
        /**
         * 当绑定到服务端的时候触发，打印"Hello world, I'm client."
         */
        @Override
        public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
            System.out.println("Hello world, I'm nettyClient.");
        }
    }
}
